import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: ()=>import('@/views/Login')
  },
  {
    path: '/home',
    name: 'home',
    redirect:'/welcome',
    meta: {
      //设置auth为true代码home页面需要鉴权
      auth:true
    },
    component: () => import('@/views/Home'),
    children:[
      { path: '/users', component: () => import('@/views/users') },
      { path: '/welcome', component: () => import('@/views/welcome') },
      { path: '/rights', component: () => import('@/views/rights/rightsList.vue') },
      { path: '/roles', component: () => import('@/views/rights/rolesList.vue') },
      { path: '/goods', component: () => import('@/views/Goods/goodsList.vue') },
      { path: '/addGoods', component: () => import('@/views/Goods/addGoods.vue') },
      { path: '/categories', component: () => import('@/views/Goods/GoodsCate.vue') },
      { path: '/params', component: () => import('@/views/Goods/GoodsParams.vue') },
      { path: '/orders', component: () => import('@/views/Orders') },
      { path: '/reports', component: () => import('@/views/reports') },
      
    ]
  }
]

const router = new VueRouter({
  routes
})


//设置路由守卫
router.beforeEach((to,from,next) => {
  console.log('to:', to)
  const flag = to.matched.some(item => {
    return item.meta.auth
  })

  //如果flag为true代表需要鉴权
  console.log('flag:',flag)
  if (flag) {
    const token = sessionStorage.getItem('token')
    if (!token) { 
     // router.push('/login')
      next({
        path:'/login'
      })
    } else {
      next()
    }
    
  } else {
    next()
  }
 
})

export default router
